<template>
  <div>
    <el-card>
      <el-row :gutter="15">
        <el-col :span="spanValue" @colchange="spanValueChange" style="overflow: auto;transition: width .2s;">
          <el-card class="leftBox" shadow="never" :body-style="{padding: '0px'}" style="overflow-y: auto;">
            <el-collapse v-model="activeName" accordion>
              <el-collapse-item name="1" v-collapseSwitch>
                <template slot="title"><span @click.stop="history='all'" style="font-size: 12px;color: #1890FF;">历史查看</span></template>
                <div class="selectArea">
                  <el-tree
                    accordion
                    ref="treeone"
                    :data="optionsType"
                    :expand-on-click-node="false"
                    node-key="value"
                    :default-expanded-keys="defaultKeys"
                    :props="{ children: 'children' }"
                    @node-click="handleTypeClick">
                    <span class="custom-tree-node" slot-scope="{ node, data }">
                      <span v-if="node.level === 3 " style="position: relative;">
                        <i v-if="data.check_flag === 1" class="el-icon-success" style="color: rgb(37 74 156);left: -20px;top:-7px;position: absolute;"></i>
                        <i v-else class="el-icon-edit" style="color: rgb(156 14 14);left: -20px;top:-7px;position: absolute;"></i>
                      </span>
                      <span :title="node.label" style="margin-right: 30px; width: 62%;text-overflow: ellipsis;overflow: hidden;">
                        <font v-if="node.level === 3" style="color: rgb(35 55 132); font-weight: bold;">{{ node.label }} </font>
                        <font v-else>{{ node.label }}</font>
                      </span>
                      <transition name="el-fade-in">
                        <span v-if="(node.key !== 0 && node.key === pgmdateCurr.value)">
                          <el-button
                            v-if="node.level === 2"
                            icon="el-icon-plus"
                            style="color: #fff;"
                            type="text"
                            size="mini"
                            title="新增"
                            v-permission="permission.add"
                            @click="dialogInfo.cu = 1">
                          </el-button>
                          <el-button
                            v-if="node.level === 3"
                            icon="el-icon-document-copy"
                            style="color: #fff;"
                            type="text"
                            title="保存模板"
                            v-permission="permission.add"
                            @click="saveTemplPgmDialog = true">
                          </el-button>
                          <el-button
                            v-if="node.level === 3"
                            icon="el-icon-delete"
                            style="color: #fff;"
                            type="text"
                            size="mini"
                            title="删除"
                            @click="deletePgmdate($event)"
                            v-permission="permission.del">
                          </el-button>
                      </span>
                      </transition>
                    </span>
                  </el-tree>
                </div>
              </el-collapse-item>
            </el-collapse>
            <el-dialog
              :title="dialogInfo.title"
              :before-close="cancelCU"
              :visible.sync="dialogInfo.cu > 0"
              width="420px"
              :close-on-click-modal="false">
              <el-form :model="pgmdateform" :rules="pgmdateformRules" ref="pgmdateformRef" label-width="90px">
                <el-form-item label="所属频道" prop="pgmgrp_name">
                  <div class="elInputS">
                    <b>{{pgmdateform.label}}</b>
                  </div>
                </el-form-item>
                <el-form-item label="节目日期">
                  <div class="elInputS">
                    <el-date-picker
                      v-model="pgmdateform.start_date"
                      align="right"
                      type="date"
                      placeholder="选择日期"
                      value-format="yyyy-MM-dd">
                    </el-date-picker>
                  </div>
                </el-form-item>
                <el-form-item label="">
                    <el-radio v-model="pgmdateform.importType" label="1">从历史日期导入</el-radio>
                    <el-radio v-model="pgmdateform.importType" label="2">模板导入</el-radio>
                </el-form-item>
                <el-form-item label="从模板导入" v-if="pgmdateform.importType === '2'">
                  <el-select v-model="pgmdateform.fromtempl" class="elInputS" placeholder="请选择节目模板">
                    <el-option label="请选择" value="0" key="-1"></el-option>
                    <el-option v-for="(item, index) in templLists" :label="item.templ_name" :value="item.templ_id" :key="index" ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="从日期导入" v-if="pgmdateform.importType === '1'">
                  <el-select v-model="pgmdateform.fromdate" class="elInputS" placeholder="请选择节目模板">
                    <el-option label="请选择" value="0" key="-1"></el-option>
                    <el-option v-for="(item, index) in dateLists" :label="item.label" :value="item.value" :key="index" ></el-option>
                  </el-select>
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button type="text" @click="cancelCU">取消</el-button>
                <el-button :loading="dialogInfo.cu === 4" type="primary" @click="submitCU">确认</el-button>
              </div>
            </el-dialog>
            <templ-pgm
              :innerVisible.sync="saveTemplPgmDialog"
              :pgmdateCurr="pgmdateCurr"
              v-if="saveTemplPgmDialog">
            </templ-pgm>
          </el-card>
        </el-col>
        <el-col :span="(24 - spanValue)" style="transition: width .2s;">
          <el-row :gutter="20" style="box-shadow: none !important;">
            <el-col :span="14">
              <!-- <time-picker inputType="readonly" v-model="timecode" /> -->
              <el-button
                type="primary"
                v-permission="permission.add"
                :icon="!innerdialogVisible? 'el-icon-folder' : 'el-icon-folder-opened'"
                @click="innerdialogVisible = !innerdialogVisible"
                :disabled="pgmgrpnode === null || [pgmgrpdialogVisible, pgmlibdialogVisible].includes(true)">素材库</el-button>
              <!-- <el-button type="danger" @click="delgrpDetail" v-permission="permission.del" icon="el-icon-delete">删除</el-button> -->
              <el-button
                type="success"
                v-permission="permission.add"
                icon="el-icon-tickets"
                @click="pgmlibdialogVisible = !pgmlibdialogVisible"
                :disabled="pgmgrpnode === null || [innerdialogVisible, pgmgrpdialogVisible].includes(true)">节目库</el-button>
              <el-button
                v-permission="permission.add"
                icon="el-icon-tickets"
                @click="pgmgrpdialogVisible = !pgmgrpdialogVisible"
                :disabled="pgmgrpnode === null || [innerdialogVisible, pgmlibdialogVisible].includes(true)">节目组</el-button>
              <el-button
               type="warning"
               icon="el-icon-circle-check"
               :disabled="checkBtnVisible"
               @click="checkLists">
                审核
              </el-button>
              <el-button
                :loading="savepgmLoading"
                type="success"
                icon="el-icon-check"
                v-if="pgmlistSave !== false"
                @click="addPgmdateDetails"
                style="margin-right: 15px;">
                保存
              </el-button>
              <!-- <el-button type="info" @click="history='all'" v-permission="permission.add" icon="el-icon-reading">历史数据</el-button> -->
              <!-- 封装的素材弹窗组件 prop:
                :innerVisible  // 控制弹窗隐藏显示
                v-model        // 接收返回的素材对象
                @change        // 选中素材改变点击确定后的回调事件.
                @close         // 弹窗点击关闭的回调事件，用于告知父组件，由父控制关闭或显示
                @replace       // 弹窗点击替换按钮的回调事件，用于处理节目替换逻辑
                mattype        // 接收3个参数（'all', 'adv', 'pgm'） 默认参数为all
              -->

              <mat-dialog
                :innerVisible="innerdialogVisible"
                v-model="matSelectRows"
                mattype="pgm"
                :multify="true"
                :drawerShow="true"
                @change="matSelectChange"
                @replace="pgmReplaceChange"
                @close="listenClose"
                @dragchange="dragAcceptRows">
              </mat-dialog>
            </el-col>
            <el-col :span="10" style="float: right; text-align: right;">
              <table-tools
                :drawerSearch="drawerVisible"
                @searchchange="searchChange"
                @refreshclick="refreshClick">
              </table-tools>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <!-- 列表区域 -->
              <el-table
                @sort-change="handleSortChange"
                @selection-change="handleSelectionChange"
                @row-contextmenu="mouseRightUp"
                :row-class-name="rowsetclassFun"
                @row-click="handleCheckRows"
                @cell-dblclick="handleCellDbClick"
                @cell-mouse-enter="handleCellMouseEnter"
                row-key="seq"
                v-loading="loading"
                height="75vh"
                ref="table"
                highlight-current-row
                :data="matlists"
                lazy
                border>
                <!-- <el-table-column :selectable="checkboxT" type="selection" width="45" /> -->
                <el-table-column prop="seq" label="序号" width="50px" align="center"></el-table-column>
                <el-table-column prop="s_time" label="开始时间" show-overflow-tooltip width="140" align="center">
                  <template v-slot="scope">
                    <div v-if="scope.row.play_mode === 3" style="display: inline-block;margin-left: 10px;margin-right: 3px;">
                      <i v-if="scope.row.ins_mode === 0" class="el-icon-right" style="font-weight: bold;"></i>
                      <i v-if="scope.row.ins_mode === 1" class="el-icon-warning" ></i>
                      <i v-if="scope.row.ins_mode === 2" style="padding-right: 13px;"></i>
                      <i v-if="scope.row.ins_mode === 3" class="el-icon-thumb"></i>
                    </div>
                    <div v-if="scope.row.seq === tabdbClickIndex && tabdbClicklabel === '开始时间'" style="display: inline-block;">
                      <time-picker ref="stimeRef" inputType="text" v-model="scope.row.s_time" @blur="tabEditBlur(scope.row.index)" />
                    </div>
                    <div v-else style="display: inline-block;">
                      <!-- <time-picker v-if="scope.row.play_mode !== 3" inputType="readonly" v-model="scope.row.s_time" /> -->
                      <time-picker inputType="readonly" v-model="scope.row.s_time_play" />
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="pgm_len" label="节目长度" show-overflow-tooltip width="140" align="center">
                  <template v-slot="scope">
                    <div v-if="scope.row.seq === tabdbClickIndex && tabdbClicklabel === '节目长度'">
                      <time-picker inputType="text" ref="pgmLenRef" @change="tabEditBlur(scope.row.index, 'change')" v-model="scope.row.pgm_len" @blur="tabEditBlur(scope.row.index)" />
                    </div>
                    <div v-else>
                      <div :class="{'back_red': scope.row.pgm_len > scope.row.true_pgm_len, 'back_yellow': scope.row.pgm_len < scope.row.true_pgm_len }">
                        <time-picker inputType="readonly" v-model="scope.row.pgm_len" />
                      </div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="pgm_name" label="节目名称" width="220" show-overflow-tooltip>
                  <template v-slot="scope">
                    <div v-if="scope.row.seq === tabdbClickIndex && tabdbClicklabel === '节目名称'">
                      <el-input type="text" ref="pgmNameRef" readonly v-model="scope.row.pgm_name" @change="tabEditBlur(scope.row.index, 'change')" @blur="tabEditBlur(scope.row.index)"></el-input>
                    </div>
                    <div v-else style="text-overflow: ellipsis;white-space: nowrap;overflow: hidden;">
                      {{scope.row.pgm_name | pgmNameTags(scope.row.grp_flag)}}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="pgm_type" label="类型" width="120" show-overflow-tooltip>
                  <template v-slot="scope">
                    {{
                      scope.row.grp_flag === 1 ? '广告' : findValLabel(scope.row.pgm_type, sysmatTypeCfg[0].children, 'mat_type_id', 'mat_type_name') || ''
                    }}
                  </template>
                </el-table-column>
                <el-table-column prop="mat_id" label="素材ID">
                  <template v-slot="scope">
                    {{ scope.row.mat_id || '' }}
                  </template>
                </el-table-column>
                <el-table-column label="播出" prop="play_mode" width="100" align="center" show-overflow-tooltip>
                  <template v-slot="scope">
                    <div v-if="scope.row.seq === tabdbClickIndex && tabdbClicklabel === '播出'">
                      <el-select
                        ref="playModeRef"
                        v-model="scope.row.play_mode"
                        v-on:change="tabEditBlur(scope.row.index, 'change')"
                        @blur="tabEditBlur(scope.row.index)">
                        <el-option
                          v-for="item in play_mode_config"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value">
                        </el-option>
                      </el-select>
                    </div>
                    <div v-else>
                      <span v-show="scope.row.play_mode === 0">定时</span>
                      <span v-show="scope.row.play_mode === 1">顺序</span>
                      <span v-show="scope.row.play_mode === 2">触发</span>
                      <span v-show="scope.row.play_mode === 3">插播</span>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="属性" width="105" align="center" show-overflow-tooltip>
                  <template v-slot="scope">
                    <div v-if="scope.row.seq === tabdbClickIndex && tabdbClicklabel === '属性'">
                      <el-select
                        ref="insModeRef"
                        v-model="scope.row.ins_mode"
                        v-on:change="tabEditBlur(scope.row.index, 'change')"
                        @blur="tabEditBlur(scope.row.index)">
                        <el-option
                          v-for="item in ins_mode_config[scope.row.play_mode]"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value">
                        </el-option>
                      </el-select>
                    </div>
                    <div v-else>
                      <span :key="item.value" v-show="scope.row.ins_mode === item.value" v-for="item in ins_mode_config[scope.row.play_mode]">{{item.label}}</span>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="信号源" show-overflow-tooltip align="center" width="110">
                  <template v-slot="scope">
                    <div v-if="scope.row.seq === tabdbClickIndex && tabdbClicklabel === '信号源'">
                      <el-select
                        ref="signSrcRef"
                        v-model="scope.row.sign_src"
                        v-on:change="tabEditBlur(scope.row.index, 'change')"
                        @blur="tabEditBlur(scope.row.index)">
                        <el-option
                          v-for="item in sign_src_config"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value">
                        </el-option>
                      </el-select>
                    </div>
                    <div v-else>
                      <span :key="item.value" v-show="scope.row.sign_src === item.value" v-for="item in sign_src_config">{{item.label}}</span>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="markin" label="链路">
                  <template v-slot="scope">
                    <span v-show="scope.row.chain_id === 0"></span>
                  </template>
                </el-table-column>
                <el-table-column prop="key1" label="Key1"></el-table-column>
                <el-table-column prop="key2" label="Key2"></el-table-column>
                <el-table-column prop="key3" label="Key3"></el-table-column>
                <el-table-column prop="key4" label="Key4"></el-table-column>
                <el-table-column label="视频格式"></el-table-column>
                <el-table-column prop="start_date" label="首播日期" width="100"></el-table-column>
                <el-table-column prop="pgm_seg" label="时段" width="100">
                  <template v-slot="scope">
                    {{ scope.row.pgm_seq || '' }}
                  </template>
                </el-table-column>
              </el-table>
              <el-dropdown @command="handleCommand" trigger="click" id="floatmousebox" ref="dropmenu" placement="bottom-start">
                <span class="el-dropdown-link"></span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="delcopy" icon="el-icon-scissors">剪切</el-dropdown-item>
                  <el-dropdown-item command="copy" icon="el-icon-document-copy">复制</el-dropdown-item>
                  <el-dropdown-item command="write" icon="el-icon-document-add">粘贴</el-dropdown-item>
                  <el-dropdown-item command="grpdetail" v-if="handleCurrentRow.grp_flag !== 0" icon="el-icon-chat-line-square">查看组明细</el-dropdown-item>
                  <el-dropdown-item command="grpopen" v-if="handleCurrentRow.grp_flag !== 0" icon="el-icon-reading">组展开</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <!-- 审核与反审弹窗 -->
              <el-dialog
                append-to-body
                :close-on-click-modal="false"
                :before-close="handlecancelCU"
                :visible.sync="checkformDialog"
                title="审核与反审"
                width="380px">
                <el-form ref="reviewform" inline :model="reviewform" label-width="85px">
                  <el-form-item label="审核意见" prop="review_word">
                     <el-input type="textarea" rows="5" v-model="reviewform.review_word"></el-input>
                  </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                  <el-button type="primary" :disabled="pgmdateCurr.check_flag === 1" @click="handlesubmitCU">审核通过</el-button>
                  <el-button type="danger" :disabled="pgmdateCurr.check_flag === 0" @click="handlesubmitNO">不通过</el-button>
                  <el-button type="brand" @click="handlecancelCU">取消</el-button>
                </div>
              </el-dialog>
              <!-- 广告组明细弹窗组件-->
              <advgrp-detail
                :innerVisible.sync="advgrpVisible"
                :scopeRow="handleCurrentRow">
              </advgrp-detail>

              <pgmgrp-detail
                :innerVisible="pgmgrpVisible"
                :scopeRow="handleCurrentRow"
                @close="pgmgrpClose">
              <!-- 节目组明细弹窗组件 -->
              </pgmgrp-detail>

              <!-- 审核校验信息弹窗 -->
              <error-dialog
                :innerVisible.sync="errorVisible"
                :errorList="errorLists"
                @rowscheck="errrowsCheck">
              </error-dialog>
              <!-- 节目组弹窗 -->
              <pgmgrp-dialog
                :pgmdateCurr="pgmdateCurr"
                :innerVisible.sync="pgmgrpdialogVisible"
                @dragchange="dragAcceptRows">
              </pgmgrp-dialog>
              <!-- 节目库弹窗组件 -->
             <pgmlib-dialog
                v-if="pgmlibdialogVisible"
                :innerVisible.sync="pgmlibdialogVisible"
                :pgmdateCurr="pgmdateCurr"
                @replace="pgmReplaceChange"
                @dragchange="dragAcceptRows">
              </pgmlib-dialog>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script>
import Sortable from 'sortablejs'
import commonMethods from '@/utils/commonMethods.js'
import editroomCommon from '@/model/editroomCommon.js' // 总编室和播出串联单公共业务逻辑
import { pgmInfoConfig } from '@/sysconfig.js' // 引入节目库系统配置
import { lists, add, del, channelpgm, channelpgmAdd, channelpgmCheck, channelpgmDel } from '@/api/makelist/channelpgm.js' // 频道列表接口
import { lists as advgrplists } from '@/api/advpgmlist/advgroup.js' // 频道列表接口
import pgmTemplApi from '@/api/makelist/pgmTempl.js' // 模板保存接口

// 引入已封装好的增删改查相关组件
import tableTools from '@/components/tableToolsComponents' // tabs工具栏组件
import MatDialog from '@/components/MatdialogComponents.vue' // 素材列表弹窗组件
import advgrpDetail from '@/components/advgrpDetailComponents.vue' // 广告组明细组件
import errorDialog from '@/components/errorDialogComponents.vue' // 错误明细弹窗
import pgmgrpDialog from '@/components/pgmgrpDialogComponents.vue' // 节目组弹窗组件
import pgmgrpDetail from '@/components/pgmgrpDetailComponents.vue' // 节目组明细弹窗组件
import pgmlibDialog from '@/components/pgmlibDialogComponents.vue' // 节目库播放安排弹窗组件
import templPgm from '@/components/templPgmComponents.vue' // 模板保存弹窗组件

export default {
  name: 'editroomlist',
  mixins: [commonMethods, editroomCommon],
  components: { tableTools, MatDialog, advgrpDetail, pgmgrpDetail, errorDialog, pgmgrpDialog, pgmlibDialog, templPgm },
  filters: {
    subTimeDate: function(value) {
      if (value !== null && value.length > 10) {
        return value.substr(0, 10)
      }
      return value
    },
    pgmNameTags: function(value, arg1) {
      if (arg1 === 1) { // 节目组
        return '【' + value + '】'
      } else if (arg1 === 2) {
        return '〖' + value + '〗'
      } else {
        return value
      }
    }
  },
  watch: {
    'dialogInfo.cu' (newValue, oldValue) {
      if (newValue === 1) {
        this.dialogInfo.title = '创建节目单'
        this.pgmdateform.channel_id = this.pgmdateCurr.value
        this.$nextTick(() => {
          this.getTemplList()
          this.getHistoryDays(this.pgmdateCurr.value) // 获取历史编单日期记录
        })
      } else if (newValue === 2) {
        this.dialogInfo.title = '重命名节目组'
        this.$set(this.pgmdateform, 'pgmgrp_name', this.pgmdateCurr.label)
        this.pgmdateform.pgmgrp_id = this.pgmdateCurr.value
        delete this.pgmdateform.channel_id
      } else if (newValue === 3) {
        this.dialogInfo.title = '复制节目组'
        this.$set(this.pgmdateform, 'pgmgrp_name', this.pgmdateCurr.label)
        this.pgmdateform.channel_id = this.pgmdateCurr.pid
      }
      this.pgmdateform.label = this.pgmdateCurr.label
    },
    'matlists' (newV, oldValue) {
      this.$nextTick(() => { // 再拖动结束视图更新后，立即对列表序号进行重新排序。
        this.matlists.forEach((item, index) => {
          if (parseInt(item.seq) !== index + 1) {
            this.pgmlistSave = true
          }
          this.$set(item, 'seq', index + 1)
        })

        this.matlists.forEach((item, index) => {
          const s_time_play = this.computedPlayTime(this.matlists, index)

          if (item.s_time_play !== undefined && item.s_time_play !== s_time_play) {
            // 第一次从服务端拿到的播出时间与前端计算后的不相等，则是前端计算播出方法与后端计算播出方法存在差异，注意检查
            console.log(item.s_time_play, s_time_play)
            this.pgmlistSave = true
          }
          // 列表计算播出时间
          this.$set(item, 's_time_play', s_time_play) // 计算节目的播出时间
        })
      })
    },
    'pgmgrpnode' (newValue, oldValue) {
      if (newValue === null) return
      this.getpgmdateDetail()
    },
    'pgmgrpnode.data.check_flag'(newValue, oldValue) {
      this.sortable.options.disabled = newValue === 1 // 审核通过后禁用排序
    },
    'CollabelVisible'(newValue) {
      console.log(newValue)
    },
    'history'(newV) {
      this.getmatTypeList()
    }
  },
  computed: {
    checkBtnVisible() {
      return (this.pgmlistSave === true && this.savepgmLoading === false) ||
        this.savepgmLoading === true ||
        [this.innerdialogVisible, this.pgmgrpdialogVisible, this.pgmlibdialogVisible].includes(true)
    }
  },
  data() {
    return {
      /* 设置页面权限 */
      timecode: 547500,
      permission: {
        add: ['admin', 'editroomlist::add'],
        edit: ['admin', 'editroomlist::edit'],
        del: ['admin', 'editroomlist::del']
      },
      play_mode_config: [
        { value: 0, label: '定时' },
        { value: 1, label: '顺序' },
        { value: 2, label: '触发' },
        { value: 3, label: '插播' }
      ],
      ins_mode_config: {
        2: [
          { value: 0, label: '手动' },
          { value: 1, label: 'BVW' },
          { value: 2, label: 'GPI' }
        ],
        3: [
          { value: 0, label: '相对' },
          { value: 1, label: '绝对' },
          { value: 2, label: '跟插' },
          { value: 3, label: '手插' }
        ]
      },
      sign_src_config: [
        { value: 0, label: 'VDR' },
        { value: 1, label: 'VTR' },
        { value: 2, label: 'LINE' }
      ],
      rules: {}, // 表单验证规则
      activeName: '1',
      optionsType: [
        {
          label: '总编室节目单',
          value: 0,
          children: []
        }
      ],
      queryInfo: {}, // 列表查询参数
      loading: false,
      drawerVisible: true,
      pgmlistSave: false, // 列表变化状态保存按钮置为disabled
      pgmInfoConfig, // 节目库系统配置
      channelList: [], // 频道列表
      innerdialogVisible: false,
      savepgmLoading: false, // 保存按钮loading
      matSelectRows: null,
      dialogInfo: {
        title: '新增节目组信息',
        cu: 0
      },
      handleCheckboxRows: [],
      matlists: [],
      pgmgrpnode: null,
      pgmdateCurr: {},
      pgmdateform: {
        start_date: this.getCurrDate(),
        fromdate: '0',
        fromtempl: '0'
      },
      pgmdateformRules: {},
      defaultKeys: [0],
      handleCurrentIndex: null,
      handleCurrentRow: {}, // 当前单选选中的rows对象
      copyhandlerows: null,
      channelnode: null, // 记录频道节点
      advgrpVisible: false, // 广告组弹窗明细组件显示开关
      pgmgrpVisible: false, // 节目组弹窗明细组件显示开关
      start_s_time: 0, //  广告节目单首播时间
      dragInsetIndex: undefined, // 素材拖拽下标

      tabdbClickIndex: null, // 双击的单元格
      tabdbClicklabel: '', // 双击单元格的列名
      checkformDialog: false,
      reviewform: {},

      // 审核错误明细弹窗
      errorVisible: false,
      errorLists: [],
      pgmlibdialogVisible: false, // 节目库弹窗组件
      pgmgrpdialogVisible: false, // 节目组弹窗显示控制
      history: 'depart', // 历史日期

      // 保存模板相关data
      saveTemplPgmDialog: false,
      templLists: [], // 模板列表数组
      dateLists: [] // 日期列表数组
    }
  },
  async created() {
    document.oncontextmenu = function (event) {
      // 阻止页面浏览器右键菜单事件
      event.preventDefault()
    }
    // console.log(this.pgmInfoConfig)
    // 获取节目类型菜单
    this.getmatTypeList()
  },
  beforeMount() {
    console.log(this.sysmatTypeCfg, 'abc')
  },
  mounted() {
    const talbody = this.$refs.table.$el.querySelectorAll('.el-table__body-wrapper')[0]
    talbody.addEventListener('click', this.handleClosereset)
    this.setSort()
    console.log(this.$refs.treeone)
  },
  activated() {
    this.getpgmdateDetail() // 缓存页面被激活后，重新获取列表数据
  },
  async beforeRouteLeave(to, from, next) {
    if (this.pgmlistSave) {
      const confirmresult = await this.$confirm('列表已修改现在要保存吗？', '提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      }).catch(err => err)
      if (confirmresult !== 'confirm') {
        next()
      }
      await this.addPgmdateDetails()
      // 是的话 则保存后弹出保存成功提示再确定离开页面。
    }
    this.$nextTick(() => {
      next()
    })
  },
  methods: {
    setSort(state) {
      const el = this.$refs.table.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
      this.sortable = new Sortable(el, {
        group: {
          name: 'shared',
          pull: 'clone'
        },
        disabled: state, // 设为false, 禁止sort
        animation: 150,
        ghostClass: 'sortable-ghost',
        onEnd: evt => {
          // console.log(this.matlists, 'target')
          const targetRow = this.matlists.splice(evt.oldIndex, 1)[0]
          this.matlists.splice(evt.newIndex, 0, targetRow)
        },
        onAdd: (evt) => {
          this.dragInsetIndex = evt.newIndex
          evt.item.remove()
        }
      })
    },
    // 获取模板列表数据
    getTemplList() {
      pgmTemplApi.lists({
        channel_id: this.pgmdateCurr.value
      }).then(res => {
        this.templLists = res.data.data
      })
    },
    // 获取所有编单历史日期
    getHistoryDays(value) {
      channelpgm({ day: 'all' }).then(res => {
        if (res.status !== 200) {
          console.log('频道分组获取失败')
        }
        this.dateLists = res.data.data.filter(item => item.value === parseInt(value))[0].children || [] // 更新日期列表
        // 对数组降序排序
        this.dateLists.sort((a, b) => {
          return new Date(b.label).getTime() - new Date(a.label).getTime()
        })
      })
    },
    // 获取频道类型列表
    getmatTypeList() {
      return new Promise((resolve, reject) => {
        channelpgm({ day: this.history }).then(res => {
          if (res.status !== 200) {
            console.log('频道分组获取失败')
          }
          this.optionsType[0].children = res.data.data
          resolve()
        })
      })
    },
    checkboxT(row, rowIndex) {
      return row.id !== false
    },
    // 列表字段排序触发监听回调
    handleSortChange(column) {
      this.queryInfo.ordername = column.prop
      this.queryInfo.order = column.order
      this.getpgmdateDetail()
    },
    // 监听列表工具搜索change事件
    searchChange(val) {
      this.drawerVisible = val
    },
    listenClose(state) {
      this.innerdialogVisible = state
    },
    // 素材列表弹窗单元行选中返回事件
    matSelectChange(val) {
      if (val !== null && val.length > 0) {
        val.map(item => {
          this.matlists.push({
            mat_id: item.mat_id,
            mat_name: item.mat_name,
            file_len: item.file_len,
            markin: item.markin,
            markout: item.markout,
            pgmgrp_id: this.pgmgrpnode.key
          })
        })
      }
    },
    getpgmdateDetail() {
      if (this.pgmgrpnode === null || this.pgmgrpnode.key === undefined) return
      // 查询节目组下素材列表信息
      this.loading = true
      this.queryInfo.type = this.pgmgrpnode.key
      lists(this.queryInfo).then(res => {
        setTimeout(() => {
          this.loading = false
          if (res.status !== 200) return
          this.matlists = res.data.data.list
          this.start_s_time = res.data.data.start_time
          this.pgmlistSave = false
          this.$nextTick(() => {
            this.pgmlistSave = false
            this.handleCurrentRow = {}
          })
        }, 150)
      })
    },
    // 向节目组下添加素材
    async addPgmdateDetails() {
      this.errorVisible = false // 关闭错误信息窗

      // 删除
      const ids = []
      ids[0] = this.pgmdateCurr.value
      this.matlists.map(item => {
        ids.push(item.seq)
      })
      this.savepgmLoading = true // 保存按钮loading 启动
      const res = await del(ids)
      if (this.matlists.length < 1 && res.status === 200) {
        this.savepgmLoading = false
        this.pgmlistSave = false
        return this.$notify({
          title: '保存成功',
          message: '节目编单保存成功！',
          type: 'success'
        })
      }

      const pgmData = this.matlists.map((item, index) => {
        return {
          pgmlist_id: item.pgmlist_id,
          seq: item.seq,
          s_time: item.s_time,
          grp_flag: item.grp_flag,
          pgm_id: item.pgm_id,
          pgm_name: item.pgm_name,
          play_mode: item.play_mode,
          ins_mode: item.ins_mode,
          pgm_type: item.pgm_type,
          pgm_len: item.pgm_len,
          sign_src: item.sign_src,
          mat_id: item.mat_id,
          tape_markin: item.tape_markin,
          tape_markout: item.tape_markout,
          play_time: item.play_time,
          start_date: item.start_date
        }
      })
      // 节目单保存提交
      add(pgmData).then(res => {
        this.savepgmLoading = false
        this.pgmlistSave = false
        return this.$notify({
          title: '保存成功',
          message: '节目编单保存成功！',
          type: 'success'
        })
      }).catch(err => {
        this.savepgmLoading = false
        this.pgmlistSave = true
        return this.$message.error(err)
      })

      /*
      // 此方式并发提交影响保存性能，已弃用
      // 生成一个promise对象数组
      const submitPromise = pgmData.map(function(data) {
        return add(data)
      })

      // 并发向服务器提交
      Promise.all(submitPromise).then(posts => {
        this.savepgmLoading = false
        this.pgmlistSave = false
        return this.$notify({
          title: '保存成功',
          message: '节目编单保存成功！',
          type: 'success'
        })
      }).catch(reason => {
        this.savepgmLoading = false
        this.pgmlistSave = false
        return this.$message.error(reason)
      }) */
    },

    // 取消
    cancelCU() {
      this.dialogInfo.cu = 0
      this.pgmdateform = {
        start_date: this.getCurrDate(),
        fromdate: '0',
        fromtempl: '0'
      }
    },
    async submitCU() {
      if (this.dialogInfo.cu === 1 || this.dialogInfo.cu === 3) { // 新增, 复制
        const findDay = this.dateLists.filter(item => item.label === this.pgmdateform.start_date)
        if (findDay.length > 0) {
          this.dialogInfo.cu = 0
          const confirm = await this.$alert(
            '总编室节目单已生成， 您要重新生成吗？',
            {
              confirmButtonText: '确定',
              showCancelButton: true,
              cancelButtonText: '取消',
              customClass: 'zdyconfirm',
              closeOnClickModal: false,
              type: 'warning'
            }
          ).catch(err => err)
          if (confirm === 'cancel') return
        }

        // 提交
        channelpgmAdd(this.pgmdateform).then(async res => {
          if (res.data.meta.status === 200 && res.data.data !== false) {
            await this.getmatTypeList()
            this.$notify({
              title: '新增成功',
              message: '节目编单生成成功！',
              type: 'success'
            })
            this.defaultKeys = [this.pgmdateform.channel_id]
            const node = this.$refs.treeone.getNode(res.data.data)
            this.handleTypeClick(node.data, node) //  checked new node
          }
          this.dialogInfo.cu = 0
        })
      }
    },
    async deletePgmdate(event) {
      event.stopPropagation()
      if (this.pgmdateCurr.check_flag === 1) {
        return this.$alert('该节目单已审核通过，不能删除！', '', {
          confirmButtonText: '确定',
          type: 'error',
          callback: function() {
            console.log('close1')
          }
        })
      }

      // console.log(this.pgmdateCurr)
      const plabel = this.$refs.treeone.getNode(this.pgmdateCurr.pid).label
      const confirmresult = await this.$confirm('您确定要删除【' + plabel + ' ' + this.pgmdateCurr.label + '】，的总编室节目单吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmresult !== 'confirm') {
        return this.$message.info('您已取消了删除')
      }
      console.log('abc')
      const ids = [this.pgmdateCurr.value]
      channelpgmDel(ids).then(res => {
        if (res.data.data.code !== 1) {
          return this.$message.error('删除失败')
        }
        this.$message.success('删除成功')
        this.getmatTypeList()
        this.defaultKeys = [this.pgmdateCurr.pid]
        this.notTipClearlist() // 无提示清空列表
      })
    },
    async delgrpDetail() {
      if (this.handleCheckboxRows.length < 1) {
        return this.$alert('请至少选中一条节目！', '', {
          confirmButtonText: '确定',
          type: 'error',
          callback: function() {
            console.log('close1')
          }
        })
      }
      const confirmresult = await this.$confirm('是否删除当前选中节目组`' + this.pgmdateCurr.label + '` 下节目信息 ，是否确定？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmresult !== 'confirm') {
        return this.$message.info('您已取消了删除')
      }

      const newData = this.matlists.filter(item => { // 获取当前节目组中新数组
        if (this.handleCheckboxRows.indexOf(item) === -1) {
          return item
        }
      })

      const matid_str = newData.map(item => {
        return item.mat_id
      }).join()

      const data = {
        pgmgrp_id: this.pgmgrpnode.key,
        mat_id: matid_str
      }

      add(data).then(res => {
        if (res.status !== 200) return
        this.pgmlistSave = false
        this.$notify({
          title: '删除成功',
          message: '节目删除成功！',
          type: 'success'
        })
        this.getpgmdateDetail()
      })
    },
    // 表格单元格双击事件
    handleCellDbClick(row, column, cell, event) {
      if (this.pgmdateCurr.check_flag === 1) {
        return this.$alert('该节目单已审核通过，不能修改！', '', {
          confirmButtonText: '确定',
          type: 'error',
          callback: function() {
            console.log('close1')
          }
        })
      }
      switch (column.label) {
        case '播出':
          this.tabdbClickIndex = row.seq
          this.tabdbClicklabel = column.label
          this.$nextTick(() => {
            this.$refs.playModeRef.focus()
          })
          break
        case '属性':
          if ([2, 3].includes(row.play_mode)) {
            this.tabdbClickIndex = row.seq
            this.tabdbClicklabel = column.label
            this.$nextTick(() => {
              this.$refs.insModeRef.focus()
            })
          }
          break
        case '信号源':
          this.tabdbClickIndex = row.seq
          this.tabdbClicklabel = column.label
          this.$nextTick(() => {
            this.$refs.signSrcRef.focus()
          })
          break
        case '节目名称':
          if (row.grp_flag === 1) {
            this.advgrpVisible = true
          } else if (row.grp_flag === 2) {
            this.pgmgrpVisible = true
          }
          break
        case '节目长度':
          this.tabdbClickIndex = row.seq
          this.tabdbClicklabel = column.label
          this.$nextTick(() => {
            this.$refs.pgmLenRef.$refs.input.focus()
          })
          break
        case '开始时间':
          if ([0, 3].includes(row.play_mode)) {
            if (row.ins_mode === 2 && row.play_mode === 3) {
              console.log(row)
            } else {
              this.tabdbClickIndex = row.seq
              this.tabdbClicklabel = column.label
              this.$nextTick(() => {
                this.$refs.stimeRef.$refs.input.focus()
              })
            }
          }
          break
        default:
      }
    },
    // 按广告类型查看
    async handleTypeClick(data, node, el) {
      if (this.pgmlistSave) {
        const confirmresult = await this.$confirm('列表已修改现在要保存吗？', '提示', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning'
        }).catch(err => err)
        if (confirmresult === 'confirm') {
          await this.addPgmdateDetails()
        }
      }

      if (this.pgmdateCurr !== data) {
        this.notTipClearlist() // 清除列表内容
      }

      this.$refs.treeone.setCurrentKey(node.key) // 设置当前节点选中
      this.channelnode = node.level === 2 ? node : null
      this.pgmgrpnode = node.level === 3 ? node : null
      this.pgmdateCurr = data
      this.pgmdateCurr.pid = node.parent.key
    },
    // 监听table列表多选checkbox多选变化事件
    handleSelectionChange(select) {
      this.handleCheckboxRows = select || []
    },
    // 列表操作栏下拉菜单指令触发方法
    async handleCommand(commond) {
      if (this.pgmdateCurr.check_flag === 1 && ['delcopy', 'copy', 'write', 'grpopen'].includes(commond)) {
        return this.$alert('该节目单已审核通过，不能修改！', '', {
          confirmButtonText: '确定',
          type: 'error',
          callback: function() {
            console.log('close1')
          }
        })
      }

      const advquery = {}
      let newdata = []
      let advgrpdata = []
      let index, _tmpindex
      switch (commond) {
        case 'delcopy':
          this.copyhandlerows = this.handleCurrentRow // 创建新的对象保存
          _tmpindex = this.matlists.indexOf(this.handleCurrentRow)
          if (_tmpindex !== undefined) {
            this.matlists.splice(_tmpindex, 1)
            this.pgmlistSave = true // 保存按钮显示
          }
          break
        case 'copy':
          this.copyhandlerows = this.handleCurrentRow // 创建新的对象保存
          break
        case 'write':
          var copyrows = JSON.parse(JSON.stringify(this.copyhandlerows))
          delete copyrows.seq
          this.matlists.splice((this.handleCurrentRow.seq), 0, copyrows)
          break
        case 'grpdetail':
          this.advgrpVisible = true
          break
        case 'grpopen':
          // 向服务端请求到展开数组
          // 数组遍历生成节目
          advquery.type = this.handleCurrentRow.adv_pl_id
          advquery.advseq = this.handleCurrentRow.pgm_id
          advgrpdata = await this.getgrpDetail(advquery)
          if (advgrpdata.list.length < 1) {
            return this.$message.error('组里没内容!')
          }
          newdata = this.matlistToPgmlist(this.handleCurrentRow, advgrpdata.list) // 将素材数组转为节目数组
          console.log(newdata)
          index = this.matlists.indexOf(this.handleCurrentRow)
          this.matlists.splice(index, 1, ...newdata)
          break
      }
    },
    matlistToPgmlist(row, data) {
      const newdata = []
      if (data.length > 0) {
        data.map((item, index) => {
          const obj = {}
          obj.s_time = (index === 0) ? row.s_time : newdata[index - 1].s_time + newdata[index - 1].pgm_len
          obj.grp_flag = 0
          obj.pgmlist_id = row.pgmlist_id
          obj.pgm_id = row.pgm_id
          obj.play_num = 0
          obj.pgm_name = item.pgm_name
          obj.play_mode = row.play_mode
          obj.ins_mode = row.ins_mode
          obj.pgm_len = item.pgm_len
          obj.pgm_type = item.pgm_type
          obj.sign_src = 0
          obj.mat_id = item.mat_id
          obj.tape_markin = 0
          obj.tape_markout = item.markout - 1
          obj.play_time = (index === 0) ? row.s_time : newdata[index - 1].s_time + newdata[index - 1].pgm_len
          newdata.push(obj)
        })
      }
      return newdata
    },
    getgrpDetail(params) {
      return new Promise((resolve, reject) => {
        advgrplists(params).then(res => {
          resolve((res.status !== 200) ? {} : res.data.data)
        }).catch((err) => {
          reject(err)
        })
      })
    },
    // 当表格单元行被鼠标右键点击时触发事件
    mouseRightUp(row, column, event) {
      this.$refs.dropmenu.visible = false
      this.$refs.table.setCurrentRow(row) // 用于单选表格，设定单元行为选中行

      // 设定操作栏浮窗相对页面位置,并显示ss。
      const dom = document.getElementById('floatmousebox')
      dom.style.left = event.clientX + 20 + 'px'
      dom.style.top = event.clientY + 'px'
      this.$refs.dropmenu.show()

      this.handleCurrentRow = row // 缓存当前右键选中行
    },
    rowsetclassFun(rowsobj) { // 单元行class 设置
      const className = []
      const { row, rowIndex } = rowsobj
      row.index = rowIndex // 把每行的索引放进row中

      if (row.play_mode === 0) { // 设置定时播放文字样式
        className.push('fontRed')
      }

      if (row.grp_flag === 1) { // 设置时段节目组背景样式
        className.push('advgrp_backgrd')
      } else if (row.grp_flag === 2) {
        className.push('pgmgrp_backgrd')
      }

      if (row.sign_src === 1) {
        className.push('sign_backgrd_blue')
      } else if (row.sign_src === 2) {
        className.push('sign_backgrd_green')
      }

      return className.join(' ')
    },
    advgrpClose() {
      this.advgrpVisible = false
    },
    pgmgrpClose(val) {
      if (val !== undefined) {
        this.handleCurrentRow.pgm_len = val
      }
      this.pgmgrpVisible = false
    },
    tabEditBlur(index, event = null) {
      if (event === 'change') {
        console.log('change')
        this.pgmlistSave = true
      }

      const copyrow = JSON.parse(JSON.stringify(this.matlists[index]))
      this.matlists.splice(index, 1, copyrow) // 重新触发watch中 对播出时间的计算行为
      setTimeout(() => {
        this.tabdbClickIndex = null
        this.tabdbClicklabel = ''
      }, 60)
    },
    handleRowsMove(rows, direction) {
      if (this.pgmdateCurr.check_flag === 1) {
        return this.$alert('该节目单已审核通过，不能修改！', '', {
          confirmButtonText: '确定',
          type: 'error',
          callback: function() {
            console.log('close1')
          }
        })
      }

      let targetRow
      switch (direction) {
        case 'Up':
          if (rows.index - 1 < 0) return this.$message.error('已移动到最顶部')
          targetRow = this.matlists.splice(rows.index, 1)[0]
          this.matlists.splice(rows.index - 1, 0, targetRow)
          break
        case 'Down':
          if (rows.index + 1 >= this.matlists.length) return this.$message.error('已移动到最底部')
          targetRow = this.matlists.splice(rows.index, 1)[0]
          this.matlists.splice(rows.index + 1, 0, targetRow)
          break
        default:
          return false
      }

      setTimeout(() => {
        this.$refs.table.setCurrentRow(this.matlists[rows.index])
      }, 20)
    },
    handleCellMouseEnter(row, column, cell, event) {
      setTimeout(() => {
        // const classArr = cell.parentElement.getAttribute('class').split(' ')
        // const index = classArr.indexOf('hover-row')
        // if (index > -1) {
        //   classArr.splice(index, 1)
        //   cell.parentElement.setAttribute('class', classArr.join(' '))
        // }
      }, 50)
    },
    async checkLists() {
      if (this.pgmdateCurr.check_flag === 0) { // 未审核通过
        const res = await this.checkPgmList()
        if (res.state) { // 校验通过
          this.checkformDialog = true
        } else {
          this.$refs.table.setCurrentRow([])
          this.errorLists = res.result || []
          this.errorVisible = true
          return this.$alert('节目单检查有误，请您修改！', '', {
            confirmButtonText: '确定',
            type: 'error',
            callback: () => {
            }
          })
        }
      } else { // 已审核通过
        this.checkformDialog = true
      }
    },
    checkPgmList() {
      return new Promise((resolve, reject) => {
        const result = []
        //  校验规则

        // 判断第一条是否是顺序，或插播节目
        if ([1, 3].includes(this.matlists[0].play_mode)) {
          result.push({
            index: 1, // 节目键
            level: 'error',
            msg: '第一条节目不能是' + (this.matlists[0].play_mode === 1 ? '顺序' : '插播') + '节目'
          })
        }

        // 判断第一条节目是否为首播时间
        if (this.matlists[0].s_time !== this.start_s_time) {
          result.push({
            index: 1, // 节目键
            level: 'warning',
            msg: '第一条节目的开始时间不等于今天的开播时间【' + this.formatMethod(this.start_s_time) + '】'
          })
        }

        this.matlists.map((item, index) => {
          const nowseq = index + 1 // 当前序号
          if (this.matlists[index].pgm_len < 125) {
            result.push({
              index: nowseq,
              level: 'warning',
              msg: `第${nowseq} 条节目【${item.pgm_name}】的长度不能小于5秒`
            })
          }

          if (index > 0) {
            if (this.matlists[index].s_time_play < this.matlists[index - 1].s_time_play) {
              result.push({
                index: nowseq,
                level: 'warning',
                msg: `第${nowseq} 条节目【${item.pgm_name}】的开始时间
                （${this.formatMethod(item.s_time_play)}）应该比第${index}条节目【${this.matlists[index].pgm_name}】的
                开始时间（${this.formatMethod(this.matlists[index - 1].s_time_play)}）晚`
              })
            }

            // 跟插节目校验
            if (this.matlists[index].play_mode === 3 && this.matlists[index].ins_mode === 2) {
              if (![3].includes(this.matlists[index - 1].play_mode)) {
                result.push({
                  index: nowseq,
                  level: 'error',
                  msg: `跟插节目前面必须是一条定插或相对插播！(第${nowseq}条节目【${item.pgm_name}】)`
                })
              }
            }

            // 相对插播校验
            if (this.matlists[index].play_mode === 3 && this.matlists[index].ins_mode === 0) {
              const play_time = this.sortPlay(this.matlists, index)
              if (this.matlists[index].s_time_play > play_time) {
                result.push({
                  index: nowseq,
                  level: 'error',
                  msg: `第${nowseq} 条插播节目【${item.pgm_name}】的插播开始时间
                      （${this.formatMethod(item.s_time)}）太晚`
                })
              }

              if (this.matlists[index - 1].play_mode === 3 && [2, 3].includes(this.matlists[index - 1].ins_mode)) {
                const exit_time = this.matlists[index - 1].s_time_play + this.matlists[index - 1].pgm_len
                if (this.matlists[index].s_time_play < exit_time && this.matlists[index].s_time_play > this.matlists[index - 1].s_time_play) {
                  result.push({
                    index: nowseq,
                    level: 'error',
                    msg: `第${nowseq}条插播节目【${item.pgm_name}】不能插在第${index}条节目【${this.matlists[index - 1].pgm_name}】内播出！`
                  })
                }
              }

              const lastinsert = this.lastInsertFind(this.matlists, index)
              if (lastinsert !== null && typeof lastinsert === 'object') {
                console.log(item, lastinsert)
                if (item.s_time <= lastinsert.s_time) {
                  result.push({
                    index: nowseq,
                    level: 'error',
                    msg: `第${nowseq}条插播节目【${item.pgm_name}】的相对插播开始时间
                    （${this.formatMethod(item.s_time)}）小于第${lastinsert.seq}条节目【${lastinsert.pgm_name}】
                    的相对插播开始时间（${this.formatMethod(lastinsert.s_time)}）`
                  })
                }
              }
            }

            // 手插节目校验
            if (this.matlists[index].play_mode === 3 && this.matlists[index].ins_mode === 3) {
              const nextInsert = this.nextInsertFind(this.matlists, index)
              console.log(nextInsert, 'abc')
              if (nextInsert !== null && typeof nextInsert === 'object') {
                result.push({
                  index: nowseq,
                  level: 'error',
                  msg: `第${nowseq}条手动插播节目【${item.pgm_name}】之后不能再有相对插播或绝对插播`
                })
              }
            }
          }
        })

        return resolve({
          state: result.length < 1,
          result
        })
      })
    },

    lastInsertFind(lists, index) {
      if (index < 0) return null
      index--
      const lastPgm = lists[index < 0 ? 0 : index]
      let lastInsert
      if ([0, 1, 2].includes(lastPgm.play_mode)) {
        lastInsert = null
      } else {
        lastInsert = lastPgm.ins_mode === 0 ? lastPgm : this.lastInsertFind(lists, index)
      }
      return lastInsert
    },
    nextInsertFind(lists, index) {
      if (lists[index] === undefined) return null
      index++
      const nextPgm = lists[index] || null
      let nextInsert
      if ([0, 1, 2].includes(nextPgm.play_mode)) {
        nextInsert = null
      } else if (nextPgm.play_mode === 3) {
        nextInsert = [0, 1].includes(nextPgm.ins_mode) ? nextPgm : this.nextInsertFind(lists, index)
      }
      return nextInsert || null
    },
    // * 审核通过 ： 正审
    handlesubmitCU() {
      channelpgmCheck({
        pl_id: this.pgmgrpnode.key,
        review_word: this.reviewform.review_word,
        review_status: 1
      }).then(res => {
        if (res.status !== 200) {
          this.$message.error('审核失败!')
        }
        this.checkformDialog = false // 关闭弹窗
        this.pgmdateCurr.check_flag = 1 // 审核状态设为已通过
        // this.pgmgrpnode.check_flag = 0
        console.log(this.pgmgrpnode)
        this.$set(this.pgmgrpnode, 'check_flag', 1)
        this.$refs.treeone.updateKeyChildren(this.pgmgrpnode.key, this.pgmgrpnode)
        return this.$message.success('审核成功!')
      })
    },
    // * 审核不通过 ： 反审
    handlesubmitNO() {
      channelpgmCheck({
        pl_id: this.pgmgrpnode.key,
        review_word: this.reviewform.review_word,
        review_status: 2
      }).then(res => {
        if (res.status !== 200) {
          this.$message.error('审核失败!')
        }
        this.checkformDialog = false // 关闭弹窗
        this.pgmdateCurr.check_flag = 0 // 审核状态设为未通过
        // this.pgmgrpnode.check_flag = 1
        this.$set(this.pgmgrpnode, 'check_flag', 0)
        console.log(this.pgmgrpnode)
        this.$refs.treeone.updateKeyChildren(this.pgmgrpnode.key, this.pgmgrpnode)
        return this.$message.success('审核成功!')
      })
    },
    handlecancelCU() {
      this.checkformDialog = false
      console.log('cancle')
    },
    errorClose() {
      this.errorVisible = false
    },
    errrowsCheck(rows) {
      this.$refs.table.setCurrentRow(this.matlists[rows.index - 1])
    }
  }
}
</script>

<style lang="less">
  .el-form-item {
    margin-bottom: 12px !important;
  }
  .operator {
    float: right;
    display: inline-block;
    margin-left: 20px;
  }
  .detailOpera .el-button {
    margin-top: 15px;
  }
  .leftBox {
    height: 81vh;
    background-color: rgba(222, 223, 230, 0.6);
  }
  .footCard {
    border:  1px solid rgba(222, 223, 230, 1);
    margin-top: 10px;
  }
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    font-size: 14px;
  }
  #floatmousebox {
    position: fixed;
  }
  .el-table tr.fontRed td{
    color: red !important;
  }

  .advgrp_backgrd {
    background-color: #def3e0 !important;
  }
  .pgmgrp_backgrd {
    background-color: #f3efde !important;
  }

  .sign_backgrd_blue {
    background-color: rgba(141, 141, 212, 0.7) !important;
  }
  .sign_backgrd_green {
    background-color: rgba(103, 193, 143, 0.7) !important;
  }

  .el-table__body tr.current-row > td {
    color: #fff;
  }

  .el-table--enable-row-hover .el-table__body tr:hover td {
    background-color: rgba(0, 0 ,0, 0) !important;
  }
  .el-table--enable-row-hover .el-table__body tr.current-row:hover>td{
    background-color: #7eadce !important;
  }
  .back_red {
    background-color: red;
    color: blue;
  }
  .back_yellow {
    background-color: yellow;
    color: blue;
  }
</style>
